<?php

namespace Muyuxuanpay\tool;
/**
 * 图片处理
 */
class Image
{
    /**
     * 图片路径转base64
     * @param string $path
     * @return string
     * @throws \Exception
     */
    public static function path2Base64(string $path)
    {
        if(empty($path)){
            throw new \Exception('图片路径不能为空');
        }
        $path = str_replace('\\', '/', $path);
        $str = file_get_contents($path);
        return base64_encode($str);
    }

    /**
     * 图片圆角处理
     * @param $filePath
     * @param $outputPath
     * @param $radius
     * @return true
     */
    public static function imageToRound($filePath,$outputPath='',$radius='')
    {
        $info = getimagesize($filePath);
        if(empty($radius)){
            if($info[0] > $info[1]){
                $radius = $info[1]/2;
            }else{
                $radius = $info[0]/2;
            }
        }
        if(empty($outputPath)){
            $outputPath = $filePath;
        }
        // 加载原始图片
        $src = imagecreatefromstring(file_get_contents($filePath));
        $width = imagesx($src);
        $height = imagesy($src);

        // 创建目标图片
        $dst = imagecreatetruecolor($width, $height);
        imagesavealpha($dst, true);
        $transparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
        imagefill($dst, 0, 0, $transparent);

        // 创建圆角蒙版
        $mask = imagecreatetruecolor($width, $height);
        $black = imagecolorallocate($mask, 0, 0, 0);
        $white = imagecolorallocate($mask, 255, 255, 255);
        imagefill($mask, 0, 0, $black);

        // 绘制圆角矩形
        imagefilledrectangle($mask, $radius, 0, $width - $radius - 1, $height - 1, $white);
        imagefilledrectangle($mask, 0, $radius, $width - 1, $height - $radius - 1, $white);

        // 绘制四个圆角
        imagefilledellipse($mask, $radius, $radius, $radius * 2, $radius * 2, $white);
        imagefilledellipse($mask, $width - $radius - 1, $radius, $radius * 2, $radius * 2, $white);
        imagefilledellipse($mask, $radius, $height - $radius - 1, $radius * 2, $radius * 2, $white);
        imagefilledellipse($mask, $width - $radius - 1, $height - $radius - 1, $radius * 2, $radius * 2, $white);

        // 应用蒙版
        for ($x = 0; $x < $width; $x++) {
            for ($y = 0; $y < $height; $y++) {
                $maskPixel = imagecolorat($mask, $x, $y) & 0xFF;
                $srcPixel = imagecolorat($src, $x, $y);
                if ($maskPixel == 0) { // 黑色部分设为透明
                    imagesetpixel($dst, $x, $y, $transparent);
                } else { // 白色部分保留原图
                    imagesetpixel($dst, $x, $y, $srcPixel);
                }
            }
        }

        imagedestroy($src);
        imagedestroy($mask);
        imagepng($dst, $outputPath);
        return true;
    }
}